import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

import 'default_error.dart';
import 'form_modal.dart';
import 'package:test_app/core/design_system/extensions/extensions.dart';

/// 单选组件（从 BaseForm 中拆分出来的独立部件）。
///
/// 保留原有的校验逻辑：
/// - 如果 require == true，则为空时提示「{label}不能为空」
Widget buildRadioFieldWidget({
  required FormModal item,
  required GlobalKey<FormBuilderFieldState> fieldKey,
  Widget Function(Widget label, Widget field)? containerBuilder,
}) {
  final List<TDRadio> options = item.options ?? const <TDRadio>[];
  final List<_RadioOption> radioOptionData = options
      .where((o) => o.id != null)
      .map(
        (o) => _RadioOption(
          id: o.id!,
          label: o.title ?? '',
          enabled: o.enable,
        ),
      )
      .toList();

  final defaultValidator = FormBuilderValidators.compose([
    FormBuilderValidators.required(errorText: '${item.label}不能为空'),
  ]);

  return FormBuilderField<String>(
    name: item.field,
    key: fieldKey,
    validator:
        item.validator ?? ((item.require ?? false) ? defaultValidator : null),
    builder: (fieldState) {
      final String? selectedValue = fieldState.value;

      final radioGroup = LayoutBuilder(
        builder: (context, constraints) {
          final mediaSize = MediaQuery.maybeOf(context)?.size;
          final double fallbackWidth = mediaSize?.width ?? 360.0;
          final double maxWidth = constraints.hasBoundedWidth && constraints.maxWidth.isFinite
              ? constraints.maxWidth
              : fallbackWidth;
          final theme = TDTheme.of(context);

          return ConstrainedBox(
            constraints: BoxConstraints(maxWidth: maxWidth),
            child: Align(
              alignment: Alignment.centerRight,
              child: Wrap(
                alignment: WrapAlignment.end,
                spacing: 12,
                runSpacing: 8,
                children: [
                  for (final option in radioOptionData)
                    _RadioChip(
                      option: option,
                      isSelected: option.id == selectedValue,
                      theme: theme,
                      onTap: option.enabled ? () => fieldState.didChange(option.id) : null,
                    ),
                ],
              ),
            ),
          );
        },
      );

      final labelWidget = Text(item.label);
      final fieldWidget = Expanded(child: radioGroup);

      final row = item.containerBuilder != null
          ? item.containerBuilder!(labelWidget, fieldWidget)
          : containerBuilder != null
          ? containerBuilder(labelWidget, fieldWidget)
          : [labelWidget, fieldWidget]
                .toRow()
                .padHorizontal(16)
                .height(58)
                .backgroundColor(const Color(0xFFFFFFFF))
                .clipRadius(8);

      return [
        row,
        if (fieldState.hasError)
          DefaultError(message: fieldState.errorText ?? ''),
      ].toColumn();
    },
  );
}

class _RadioOption {
  final String id;
  final String label;
  final bool enabled;

  const _RadioOption({
    required this.id,
    required this.label,
    required this.enabled,
  });
}

class _RadioChip extends StatelessWidget {
  final _RadioOption option;
  final bool isSelected;
  final TDThemeData theme;
  final VoidCallback? onTap;

  const _RadioChip({
    required this.option,
    required this.isSelected,
    required this.theme,
    this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    final Color borderColor = isSelected ? theme.brandNormalColor : theme.grayColor3;
    final Color textColor = option.enabled
        ? (isSelected ? theme.brandNormalColor : theme.fontGyColor1)
        : theme.fontGyColor4;
    final Color iconColor = option.enabled
        ? (isSelected ? theme.brandNormalColor : theme.grayColor4)
        : theme.grayColor5;

    final chip = Container(
      constraints: const BoxConstraints(minHeight: 36),
      padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(999),
        border: Border.all(color: borderColor, width: 1),
        color: isSelected
            ? theme.brandColor1.withValues(alpha: 0.08)
            : Colors.white,
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            isSelected ? TDIcons.check_circle_filled : TDIcons.circle,
            size: 18,
            color: iconColor,
          ),
          const SizedBox(width: 6),
          Text(
            option.label,
            style: TextStyle(
              fontSize: 14,
              color: textColor,
            ),
          ),
        ],
      ),
    );

    if (onTap == null) {
      return Opacity(opacity: 0.6, child: chip);
    }

    return InkWell(
      borderRadius: BorderRadius.circular(999),
      onTap: onTap,
      child: chip,
    );
  }
}
